package com.yuchen.ishop.web.app;


import com.yuchen.ishop.service.file.FileRequest;
import com.yuchen.ishop.service.file.FileRestClient;
import com.yuchen.ishop.vo.FileResponse;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.utils.config.ConfigUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping(value = "/kindEditor")
public class KindEditorAction extends BaseAction{

    @Autowired
    private FileRestClient fileRestClient;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map uploadGoodsImg(HttpServletRequest request) throws Exception {
        Map map = new HashMap(2);
        try {
            // Goods goods = new Goods();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("imgFile");
            if (null != files && files.size() > 0) {
                for (MultipartFile file : files) {
                    String type = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
                    FileRequest req = new FileRequest(type,"attach",file.getInputStream());
                    FileResponse response = fileRestClient.sendFile(req);
                    if(response.getStatus()){
                        map.put("error",0);
                        String fileServer =  ConfigUtils.config.get("fileServerUrl");
                        map.put("url",fileServer+"/"+response.getPath());
                        return map;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        map.put("error",1);
        map.put("message","上传失败！");
        return map;
    }

}
